package com.mlz.mlzmall.ui.activity.act.personal;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.google.gson.Gson;
import com.mlz.mlzmall.R;
import com.mlz.mlzmall.bean.StatusBean;
import com.mlz.mlzmall.bean.UserBean;
import com.mlz.mlzmall.ui.activity.act.base.TopTitleView;
import com.mlz.mlzmall.ui.activity.act.main.MyApplication;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.VolleyBaseActivity;
import com.mlz.mlzmall.ui.utils.mlz.ConfigInfo;
import com.mlz.mlzmall.ui.utils.mlz.URL;
import com.mlz.mlzmall.ui.utils.util.LogUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * Created by adminitator on 2016/5/18.
 */
public class ChangeNameActivity extends VolleyBaseActivity {

    private ImageView ivClean;//清除名称
    private Button btnSave;//保存
    private EditText etChangeName;//修改名称

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.change_name);//个人属性界面
        initView();
        initText();//用户名改变来确定清除键是否存在
        getCollection();
        setViewContent();
    }
    private void setViewContent() {
        TopTitleView loginTopTitle = (TopTitleView) findViewById(R.id.login_top_title);
        loginTopTitle.setLeftButtonContent("个人信息", R.mipmap.pic_2_1_btn_back, null);
        loginTopTitle.setTitleButtonContent("修改姓名", null, null);
        loginTopTitle.setOnLeftButtonClickListener(new TopTitleView.OnLeftButtonClickListener() {
            @Override
            public void onLeftBtnClick(View button) {
                finish();
                ChangeNameActivity.this.overridePendingTransition(R.anim.right_in,R.anim.right_out);
            }
        });
    }
    /**
     * 添加判断收藏请求参数和添加收藏请求参数
     */
    private Map<String, String> getMall2() {
        Map<String, String> param1 = new HashMap<>();
        param1.put("productId", "7157");
        return param1;
    }

    /**
     * 判断商品是否已收藏,是弹出已添加，不是就收藏
     */
    public void getCollection() {
        tag = "getCollection";
        JSONObject jsonObject = new JSONObject(getMall2());
        JsonRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, URL.WISHLIST.ISIN, jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                LogUtils.d(jsonObject.toString());

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(tag, error.getMessage(), error);

            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put(ConfigInfo.CHARSET, ConfigInfo.UTF8);
                map.put(ConfigInfo.COOKIE, ConfigInfo.COOKIE_KEY + sessionId);
                map.put(ConfigInfo.TYPE, ConfigInfo.TYPE_KEY);
                return map;
            }
        };

        // 设置该请求的标签
        jsonRequest.setTag(tag);
        // 将请求添加到队列中
        ((MyApplication) getApplication()).getRequestQueue().add(jsonRequest);
    }

    private void initView() {
        ivClean = (ImageView) findViewById(R.id.iv_clean);
        btnSave = (Button) findViewById(R.id.btn_save);
        etChangeName = (EditText) findViewById(R.id.et_change_name);
        etChangeName.setText(isNull(MyApplication.getInstance().getLoginUser().getUserName()));
        etChangeName.setSelection(etChangeName.getText().length());//将光标设置在文字后面
        ivClean.setOnClickListener(this);
        btnSave.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_clean:
                etChangeName.setText("");
                // ivClean.setVisibility(View.GONE);
                break;
            case R.id.btn_save:
                String userName = etChangeName.getText().toString();
                if (userName.length() == 0) {
                    showToast("用户名不能为空!");
                } else {
                    postChangeName(userName);
                }
                break;
        }
    }

    private void initText() {//用户名改变来确定清除键是否存在
        etChangeName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
                    ivClean.setVisibility(View.GONE);
                } else {
                    ivClean.setVisibility(View.VISIBLE);
                }
            }
        });
    }


    private void postChangeName(final String userName) {
        tag = "rPost";
        Map<String, String> paraml = new HashMap<>();
        paraml.put("fullname", userName);

        JSONObject jsonObject = new JSONObject(paraml);
        JsonRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, URL.CUSTOMER.EDIT_NAME, jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Gson gson = new Gson();
                StatusBean sb = gson.fromJson(jsonObject.toString(), StatusBean.class);
                if (sb.getStatus() == 0) {
                    showToast("修改成功");
                    UserBean ub = new UserBean();
                    ub.setUserName(userName);
                    Intent it = new Intent();
                    setResult(101, it);
                }
                finish();
                ChangeNameActivity.this.overridePendingTransition(R.anim.right_in, R.anim.right_out);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(tag, error.getMessage(), error);
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put(ConfigInfo.CHARSET, ConfigInfo.UTF8);
                map.put(ConfigInfo.COOKIE, ConfigInfo.COOKIE_KEY + sessionId);
                map.put(ConfigInfo.TYPE, ConfigInfo.TYPE_KEY);
                return map;
            }
        };
        //设置该请求的标签
        jsonRequest.setTag(tag);
        //将请求添加到请求队列中
        ((MyApplication) getApplication()).getRequestQueue().add(jsonRequest);
    }
}
